package com.enjoyor.soa.traffic.util.helper;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.SocketException;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;

/**
 * @Title: FileUtil.java
 * @Description: TODO(用一句话描述该文件做什么)
 * @author sxh
 * @date 2018年2月27日 下午6:37:31
 * @version V1.0
 */
public class FileToStreamHelp {
    private static Logger logger = Logger.getLogger(FileToStreamHelp.class);

    /**
     * 
     * 读取文件，文件路径支持本地文件、Ftp文件、http文件，返回字节流
     * 
     * @param filePath
     * @throws Exception
     */
    public static InputStream getFile(String filePath) throws Exception {
        if (filePath.toLowerCase().startsWith("ftp://")) {
            int pathStart = filePath.indexOf("/", 6);
            String strIp = filePath.substring(6, pathStart);
            String strPath = filePath.substring(pathStart + 1, filePath.lastIndexOf("/"));
            String fileName = filePath.substring(filePath.lastIndexOf("/") + 1, filePath.length());
            String userId = "";
            String password = "";
            int port = 21;
            if (strIp.contains("@")) {
                String[] strUserIp = strIp.split("@");
                userId = strUserIp[0].split(":")[0];
                password = strUserIp[0].split(":")[1];
                strIp = strUserIp[1];
            }
            if (strIp.contains(":")) {
                port = Integer.parseInt(strIp.split(":")[1]);
                strIp = strIp.split(":")[0];
            }
            return downloadFtpFile(strIp, userId, password, port, strPath, fileName);
        } else if (filePath.toLowerCase().startsWith("http://") || filePath.toLowerCase().startsWith("https://")) {
            return httpDownload(filePath);
        }
        return null;
    }

    /*
     * 从FTP服务器下载文件
     * @param ftpHost FTP IP地址
     * @param ftpUserName FTP 用户名
     * @param ftpPassword FTP用户名密码
     * @param ftpPort FTP端口
     * @param ftpPath FTP服务器中文件所在路径 格式： ftptest/aa
     * @param localPath 下载到本地的位置 格式：H:/download
     * @param fileName 文件名称
     */
    public static InputStream downloadFtpFile(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort,
            String ftpPath, String fileName) {

        FTPClient ftpClient = null;
        InputStream is = null;
        try {
            ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort);
            ftpClient.setControlEncoding("UTF-8"); // 中文支持
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            ftpClient.changeWorkingDirectory(ftpPath);

            // 连接后再取流
            Thread.sleep(100);

            is = ftpClient.retrieveFileStream(fileName);
            // ftpClient.logout();
        } catch (FileNotFoundException e) {
            logger.error("没有找到" + ftpPath + "文件");
            e.printStackTrace();
        } catch (SocketException e) {
            logger.error("连接FTP失败.");
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("文件读取错误。");
            e.printStackTrace();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return is;
    }

    /**
     * 获取FTPClient对象
     * 
     * @param ftpHost
     *            FTP主机服务器
     * @param ftpPassword
     *            FTP 登录密码
     * @param ftpUserName
     *            FTP登录用户名
     * @param ftpPort
     *            FTP端口 默认为21
     * @return
     */
    public static FTPClient getFTPClient(String ftpHost, String ftpPassword, String ftpUserName, int ftpPort) {
        FTPClient ftpClient = null;
        try {
            ftpClient = new FTPClient();
            ftpClient.connect(ftpHost, ftpPort);// 连接FTP服务器
            ftpClient.login(ftpUserName, ftpPassword);// 登陆FTP服务器
            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                logger.info("未连接到FTP，用户名或密码错误。");
                ftpClient.disconnect();
            } else {
                logger.info("FTP连接成功。");
            }
        } catch (SocketException e) {
            logger.error("FTP的IP地址可能错误，请正确配置。", e);
        } catch (IOException e) {
            logger.error("FTP的端口错误,请正确配置。", e);
        }
        return ftpClient;
    }

    @SuppressWarnings("unused")
    public static InputStream httpDownload(String urlPath) {
        InputStream in = null;
        File file = null;
        try {
            // 统一资源
            URL url = new URL(urlPath);
            // 连接类的父类，抽象类
            URLConnection urlConnection = url.openConnection();
            // http的连接类
            HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
            // 设定请求的方法，默认是GET
            httpURLConnection.setRequestMethod("GET");
            // 设置字符编码
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            // 打开到此 URL 引用的资源的通信链接（如果尚未建立这样的连接）。
            httpURLConnection.connect();
            // 文件大小
            int fileLength = httpURLConnection.getContentLength();
            // 文件名
            String filePathUrl = httpURLConnection.getURL().getFile();
            String fileFullName = filePathUrl.substring(filePathUrl.lastIndexOf(File.separatorChar) + 1);
            URLConnection con = url.openConnection();
            in = new BufferedInputStream(httpURLConnection.getInputStream());
        } catch (Exception e) {
            logger.error("下载http文件出错。", e);
        }
        return in;
    }
}
